package com.lanou.renrenxin.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.adapter.ChattingAdapter;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.custommodule.LongClickDialog;
import com.lanou.renrenxin.dao.ChatList;
import com.lanou.renrenxin.onclicklistener.DialogClickListener;
import com.lanou.renrenxin.onclicklistener.LimitTimeListener;
import com.lanou.renrenxin.onclicklistener.OnChattingItemClickListener;
import com.lanou.renrenxin.singleton.RenrenxinSingleton;
import com.lanou.renrenxin.tools.ChatLogger;
import com.lanou.renrenxin.tools.RecorderVoice;
import com.lanou.renrenxin.tools.RenTextUtils;
import com.lanou.renrenxin.tools.SendMessage;
import com.lanou.renrenxin.tools.StringValues;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by zouhui on 16/3/3.
 */
public class ChattingActivity extends BaseActivity implements View.OnClickListener, OnChattingItemClickListener, View.OnTouchListener, TextWatcher, LimitTimeListener, DialogClickListener {
    private static final int REQUEST_IMAGE = 2;
    private static final int REQUEST_LOCATION = 33;
    private String username;
    private String mUsername;
    private ImageButton backBtn, userBtn, voiceOrText, moreBtn,
            addImageBtn, addVideoBtn, addlocationBtn, addFileBtn;
    private RecyclerView recyclerView;
    private EditText messageBody;
    private Button sendBtn, sendVoice;
    private LinearLayout linearLayout;
    private TextView usernameTv;
    //recycleview适配器
    private ChattingAdapter adapter;
    private BroadcastReceiver deliveryAckMessageReceiver;
    private LinearLayoutManager linearLayoutManager;
    private NewMessageBroadcastReceiver msgReceiver;
    private ChattingAdapter.ChattingSendViewHolder holder;
    private int count = 0;//记录点击语音或文本按钮的次数
    private int moreCount = 0;//记录更多点击次数
    private Handler handler;
    private RecorderVoice recorderVoice;
    private String isSend = "";
    private RelativeLayout.LayoutParams layoutParams;
    private ArrayList<String> mSelectPath;
    private ChattingAdapter.ChattingSendImageViewHolder sendImageViewHolder;
    private SendMessage sendMessage;
    private CallReceiver callReceiver;
    private LongClickDialog clickDialog;
    private String longClickBody;
    private String longClickMsgId;

    private EMMessage fragmentMessage;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatting);
        //只有注册了广播才能接收到新消息，目前离线消息，在线消息都是走接收消息的广播
        // （离线消息目前无法监听，在登录以后，接收消息广播会执行一次拿到所有的离线消息）
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter =
                new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(4);
        registerReceiver(msgReceiver, intentFilter);
        registerBroadCast();

        //实时通话广播注册
        IntentFilter callFilter = new IntentFilter(EMChatManager.getInstance().getIncomingCallBroadcastAction());
        callReceiver = new CallReceiver();
        registerReceiver(callReceiver, callFilter);
        findId();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 105) {
                    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                }
                if (msg.what == 106) {
                    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                }
                if (msg.what == 230) {
                    sendImageViewHolder = (ChattingAdapter.ChattingSendImageViewHolder) msg.obj;
                }
                if (msg.what == 222&&sendImageViewHolder!=null) {
                    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                    sendImageViewHolder.imageView.setProgress((Integer) msg.obj);
                    if ((Integer) msg.obj == 100) {
                        sendImageViewHolder.imageView.setProgress(101);
                    }


                }

                return false;
            }
        });


    }


    @Override
    protected void onResume() {
        super.onResume();
        RenrenxinSingleton.getInstence().loadHeadImage(username);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
        unregisterReceiver(callReceiver);
    }



    private void registerBroadCast() {
        EMChatManager.getInstance().getChatOptions().setRequireDeliveryAck(false);
        //如果用到已发送的回执需要把这个flag设置成true
        IntentFilter deliveryAckMessageIntentFilter =
                new IntentFilter(EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
        deliveryAckMessageIntentFilter.setPriority(5);
        registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

        /**
         * 消息送达BroadcastReceiver
         */
        deliveryAckMessageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                abortBroadcast();

                String msgid = intent.getStringExtra("msgid");
                String from = intent.getStringExtra("from");
                EMConversation conversation = EMChatManager.getInstance().getConversation(from);
                if (conversation != null) {
                    // 把message设为已读
                    EMMessage msg = conversation.getMessage(msgid);
                    if (msg != null) {
                        msg.isDelivered = true;
                    }
                }
            }
        };
    }


    /**
     * 加载控件
     */
    private void findId() {
        Intent intent = getIntent();
        username = intent.getStringExtra("USER_NAME");
        mUsername = intent.getStringExtra("M_USER_NAME");

        recorderVoice = new RecorderVoice();

        linearLayout = (LinearLayout) findViewById(R.id.ll_activity_chatting);
        userBtn = (ImageButton) findViewById(R.id.iv_activity_chatting_user);
        usernameTv = (TextView) findViewById(R.id.tv_activity_chatting_username);
        recyclerView = (RecyclerView) findViewById(R.id.recycle_activity_chatting);
        messageBody = (EditText) findViewById(R.id.editText_activity_chatting_body);
        voiceOrText = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_voiceortext);
        moreBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_send_more);
        sendVoice = (Button) findViewById(R.id.btn_activity_chatting_sendvoice);
        sendBtn = (Button) findViewById(R.id.btn_activity_chatting_send);
        addImageBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_Image);
        addVideoBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_video);
        addlocationBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_location);
        addFileBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_file);
        backBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_back);

        addImageBtn.setOnClickListener(this);
        addFileBtn.setOnClickListener(this);
        addlocationBtn.setOnClickListener(this);
        addVideoBtn.setOnClickListener(this);
        usernameTv.setText(username);
        messageBody.addTextChangedListener(this);
        sendBtn.setOnClickListener(this);
        sendVoice.setOnTouchListener(this);
        moreBtn.setOnClickListener(this);
        voiceOrText.setOnClickListener(this);
        userBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        recorderVoice.setLimitTimeListener(this);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setOnTouchListener(this);
        adapter = new ChattingAdapter(this, username, mUsername);
        adapter.setOnChattingItemClickListener(this);
        recyclerView.setAdapter(adapter);
        sendMessage = new SendMessage(adapter, handler, recyclerView,username);
        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgBtn_activity_chatting_back:
                finish();
                break;
            case R.id.btn_activity_chatting_send:
                // TODO: 16/3/3 发送消息
                sendMessage.sendTextMessage(content(), mUsername, username, obtainTime());
                recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                moreBtn.setVisibility(View.VISIBLE);
                sendBtn.setVisibility(View.GONE);
                break;
            case R.id.iv_activity_chatting_user:
                // TODO: 16/3/3 删除聊天记录
               showDeleteDialog();
                break;
            case R.id.imgBtn_activity_chatting_send_more:
                // TODO: 16/3/5 更多
                linearLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.imgBtn_activity_chatting_voiceortext:
                if (count % 2 == 0) {
                    messageBody.setVisibility(View.GONE);
                    sendVoice.setVisibility(View.VISIBLE);
                    voiceOrText.setImageResource(R.mipmap.voice);
                    count++;
                } else {
                    messageBody.setVisibility(View.VISIBLE);
                    sendVoice.setVisibility(View.GONE);
                    voiceOrText.setImageResource(R.mipmap.text);
                    count++;
                }
                break;
            case R.id.imgBtn_activity_chatting_add_Image:
                // TODO: 16/3/8 发送图片
                selectImage();
                break;
            case R.id.imgBtn_activity_chatting_add_video:
                // TODO: 16/3/8 发送视频
                SelectCallPopupWindow  menuWindow = new SelectCallPopupWindow(this, username);
                //显示窗口
                menuWindow.showAtLocation(this.findViewById(R.id.relative_activity_chatting),
                        Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                break;
            case R.id.imgBtn_activity_chatting_add_location:
                Intent locationIntent = new Intent(this,LocationFilter.class);
                locationIntent.putExtra(StringValues.USER_NAME,username);
                startActivityForResult(locationIntent, REQUEST_LOCATION);
                break;
            case R.id.imgBtn_activity_chatting_add_file:
                // TODO: 16/3/8 发送文件
                Intent fileIntent = new Intent(this, FileSelectorActivity.class);
                fileIntent.putExtra(FileSelectorActivity.keyClassName, ChattingActivity.class.getName());
                fileIntent.putExtra(FileSelectorActivity.keyIsSelectFile,true);
                fileIntent.putExtra(FileSelectorActivity.keyIsSingleSelector, false);
                startActivityForResult(fileIntent, FileSelectorActivity.requestCodeSingleFile);
                break;
        }
    }

    private void showDeleteDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("清除聊天记录");
        builder.setMessage("您确定清除该会话聊天记录吗？(包括本地记录)");
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ChatLogger chatLogger = new ChatLogger(username);
                chatLogger.deleteOneLogger();
                adapter.notifyDataSetChanged();
                Toast.makeText(ChattingActivity.this, "删除成功", Toast.LENGTH_SHORT).show();

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }


    private void selectImage() {
        mSelectPath = new ArrayList<>();
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        boolean showCamera = true;
        int maxNum = 9;
        Intent intent = new Intent(ChattingActivity.this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, showCamera);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择

        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }


    private String obtainTime() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//24小时制
        String time = sdformat.format(calendar.getTime());
        return time;
    }

    private String content() {
        String content = messageBody.getText().toString();
        messageBody.setText("");
        if (content.equals("")) return null;
        return content;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SendMessage resultSendMessage = new SendMessage(adapter, handler, recyclerView,username);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK&&data!=null) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    resultSendMessage.sendImage(mSelectPath.get(i), mUsername, username, obtainTime());
                }
            }
        }
        if (requestCode == REQUEST_LOCATION) {
            if (data!=null) {
                String locationString = data.getStringExtra(StringValues.LOCATION_STRING);
                Double latitude = data.getDoubleExtra(StringValues.LATITUDE, 38.889784);
                Double longitude = data.getDoubleExtra(StringValues.LONGITUDE, 121.55076);
                recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                resultSendMessage.sendLocation(locationString, latitude, longitude, username, mUsername);
            }
        }

        if(requestCode == FileSelectorActivity.requestCodeSingleFile&&null!=data){
            ArrayList<String> list = data.getStringArrayListExtra(FileSelectorActivity.keyFilePaths);
            for (int i=0;(list!=null) && (i<list.size());i++){
                sendMessage.sendFile(list.get(i),mUsername);
            }


        }

    }


    /**
     * 头像点击事件
     *
     * @param username
     */
    @Override
    public void onHeadImgClick(String username) {
        Intent intent = new Intent(this, PIMActivity.class);
        intent.putExtra("PIM_USER_NAME", mUsername);
        intent.putExtra("detail", username);
        startActivity(intent);
    }

    /**
     * 图片点击事件
     * @param path
     */
    @Override
    public void onImageClick(String path,boolean isSend) {
        Intent intent = new Intent(this, ImageActivity.class);
        intent.putExtra(StringValues.IMAGE_PATH, path);
        intent.putExtra(StringValues.IMAGE_ISSEND,isSend);
        startActivity(intent);
    }

    /**
     * 聊天记录长按事件处理
     *
     * @param username
     */
    @Override
    public void onChattingItemLongClick(String username,String body,String msgId,EMMessage emMessage) {
        longClickBody = body;
        longClickMsgId = msgId;
        fragmentMessage = emMessage;
        showMyDialog();
    }

    /**
     * 播放语音
     *
     * @param path
     */
    @Override
    public void playVoice(String path) {
        recorderVoice.playVoice(path);
    }

    /**
     * 点击地图Item
     * @param latitude
     * @param longitude
     */
    @Override
    public void onLocationItemClick(double latitude, double longitude) {
        Intent intent = new Intent(this,LocationFilter.class);
        intent.putExtra(StringValues.GO_LATITUDE,latitude);
        intent.putExtra(StringValues.GO_LONGITUDE,longitude);
        intent.putExtra(StringValues.FIND_LOCATION,true);
        startActivity(intent);
    }


    /**
     * 显示消息处理对话框
     */
    private void showMyDialog() {
        clickDialog = new LongClickDialog();
        Bundle bundle = new Bundle();
        bundle.putParcelable(StringValues.DIALOG_EMMESSAGE,fragmentMessage);
        clickDialog.setArguments(bundle);
        clickDialog.setDialogClickListener(this);
        clickDialog.show(getFragmentManager(), "sss");
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.recycle_activity_chatting){
          linearLayout.setVisibility(View.GONE);
        }else {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    recorderVoice.recorderVoice();
                    break;
                case MotionEvent.ACTION_UP:
                    if (!isSend.equals(recorderVoice.getPaths())) {
                        recorderVoice.stopRecorder();
                        sendMessage.sendVoice(recorderVoice.getPaths(),
                                recorderVoice.getLen(), mUsername, username, recorderVoice, isSend);
                    }
                    break;
            }
        }
        return false;
    }


    /**
     * EditText 文本变化以前
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        moreBtn.setVisibility(View.VISIBLE);
        sendBtn.setVisibility(View.GONE);
    }

    /**
     * EditText 文本变化时
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        moreBtn.setVisibility(View.GONE);
        sendBtn.setVisibility(View.VISIBLE);
        if (messageBody.getText().toString().equals("")) {
           linearLayout.setVisibility(View.GONE);
            moreBtn.setVisibility(View.VISIBLE);
            sendBtn.setVisibility(View.GONE);

        }
    }

    /**
     * EditText 文本变化后
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 限时发送自动发送语音
     */
    @Override
    public void limitTime() {
        sendMessage.sendVoice(recorderVoice.getPaths(), recorderVoice.getLen(), mUsername, username, recorderVoice, isSend);
        Toast.makeText(this, "最多可以\r\n录制60秒", Toast.LENGTH_SHORT).show();


    }




    /**
     * 复制聊天记录
     */
    @Override
    public void copyMsg() {
        RenTextUtils.copy(longClickBody,this);
        clickDialog.dismiss();
    }

    /**
     * 转发聊天记录
     */
    @Override
    public void forwardMsg(EMMessage emMessage) {
        Intent intent = new Intent(this,ForwardAMsgActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable(StringValues.DIALOG_EMMESSAGE_FORWARD,emMessage);
        intent.putExtras(bundle);
        startActivity(intent);
        clickDialog.dismiss();
    }

    /**
     *删除聊天记录
     */
    @Override
    public void deleteMsg() {
        ChatLogger chatLogger = new ChatLogger(username);
        chatLogger.deleteSingleLogger(longClickMsgId);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(adapter.getItemCount()-1);
        clickDialog.dismiss();
    }

    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 截断广播
            abortBroadcast();
            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            ChatList chat = new ChatList();
            String body = "";
            String msgType = "";

            if (message.getType() == EMMessage.Type.TXT) {
                msgType = StringValues.MSG_TYPE_TXT;
                body = ((TextMessageBody) message.getBody()).getMessage();
            } else if (message.getType() == EMMessage.Type.FILE) {
                body = "[文件]"+((FileMessageBody)message.getBody()).getFileName();
                msgType = StringValues.MSG_TYPE_FILE;
            } else if (message.getType() == EMMessage.Type.IMAGE) {
                msgType = StringValues.MSG_TYPE_IMAGE;
                body = "[图片]";
            } else if (message.getType() == EMMessage.Type.LOCATION) {
                msgType = StringValues.MSG_TYPE_LOCATION;
                body = "[位置]"+((LocationMessageBody)message.getBody()).getAddress();
            } else if (message.getType() == EMMessage.Type.VOICE) {
                msgType = StringValues.MSG_TYPE_VOICE;
                body = "[语音]";
            } else if (message.getType() == EMMessage.Type.VIDEO) {
                msgType = StringValues.MSG_TYPE_VIDEO;
            }
            chat.setBody(body);
            chat.setMsg_type(msgType);
            chat.setUsername(message.getUserName());
            chat.setMUsername(mUsername);
            chat.setType(1);
            adapter.notifyDataSetChanged();
            recyclerView.scrollToPosition(adapter.getItemCount()-1);
            RenrenxinSingleton.getInstence().saveChatList(chat);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
        }
    }

    /**
     * 实时通话广播接收者
     */
    private class CallReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            // 拨打方username
            String from = intent.getStringExtra("from");
            // call type
            String type = intent.getStringExtra("type");
            Toast.makeText(context, "视频来了", Toast.LENGTH_SHORT).show();
            if("video".equals(type)){ //视频通话
                context.startActivity(new Intent(context, VideoCallActivity.class).
                        putExtra("username", from).putExtra("isComingCall", true).
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }else{ //音频通话
                context.startActivity(new Intent(context, VoiceCallActivity.class).
                        putExtra("username", from).putExtra("isComingCall", true).
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }
        }
    }



}
